<?php
namespace Api\Controller;
use Common\Controller\BaseController;
use Common\Conf\Constants;
use Common\Library\Rong\RongpayService;
/**
 * 支付通知
 *
 * @since: 2016年12月30日 下午3:37:43
 * @author: xielu
 * @version: V1.0.0
 */
class BackController extends BaseController {

    // 商户ID，由纯数字组成的字符串
    protected $merchant_id ;
    // 交易安全检验码，由数字和字母组成的64位字符串
    protected $apiKey ;
    //签约融宝支付账号或卖家收款融宝支付帐户
    protected $seller_email;
    //商户私钥
    protected $merchantPrivateKey;
    //融宝公钥
    protected $reapalPublicKey;

    /**
     * 初始化
     *
     * @since: 2016年12月27日 下午5:21:44
     * @author: lyx
     * @change xl
     */
    public function _initialize() {
        parent::_initialize();
        $this->merchant_id = $this->sys_config['PAY_MERCHANT_ID'];
        $this->apiKey = $this->sys_config['PAY_APIKEY'];
        $this->seller_email = $this->sys_config['PAY_SELLER_EMAIL'];
        $this->merchantPrivateKey = $this->sys_config['PAY_PRIVAT_EKEY'];
        $this->reapalPublicKey = $this->sys_config['PAY_PUBLIC_KEY'];
    }
    /**
     * 同步通知
     *
     * @since: 2016年3月11日 下午3:21:44
     * @change xl
     */
    public function returnNow()
    {
        $data = $_POST['data'];
        $encryptkey = $_POST['encryptkey'];
        $order_no = $this->check($data,$encryptkey);
        if($order_no){
            redirect(U('Home/Cash/index',array('order_no'=>$order_no)));
        }else{
            redirect(U('Home/Cash/payList'));
        }
    }

    /**
     * 异步通知
     *
     * @since: 2016年3月11日 下午3:21:44
     * @change xl
     */
    public function returnPage()
    {
        error_reporting(E_ALL || ~E_NOTICE);
        $data = $_POST['data'];
        $encryptkey = $_POST['encryptkey'];
        $this->check($data,$encryptkey);
    }

    /**
     * 回调处理
     *
     * @param $data 数据体
     * @param $encryptkey 加密信息
     * @return mixed 订单号
     * @since: 2016年3月11日 下午3:21:44
     * @change xl
     */
    private function check($data,$encryptkey)
    {
        //解密
        $encryptkey = RongpayService::RSADecryptkey($encryptkey,THINK_PATH.'../'.$this->merchantPrivateKey);
        $decryData = RongpayService::AESDecryptResponse($encryptkey, $data);
        $jsonObject = json_decode($decryData,true);

        $merchant_id = $jsonObject['merchant_id'];
        $trade_no = $jsonObject['trade_no'];
        $order_no = $jsonObject['order_no'];
        $total_fee = $jsonObject['total_fee'];
        $status = $jsonObject['status'];
        $sign = $jsonObject['sign'];
        $notify_id = $jsonObject['notify_id'];
        $paramarr = array(
            'merchant_id' => $merchant_id,
            'trade_no' => $trade_no,
            'order_no' => $order_no,
            'total_fee' => $total_fee,
            'status' => $status,
            'notify_id' => $notify_id
        );

        $mysign = RongpayService::createSign($paramarr,$this->apiKey);
        if ($mysign === $sign){
            $order =  D('Pay')->where(array('order_no'=>$order_no))->find();
            if($order){
                if($status === "TRADE_FINISHED"){
                    echo 'success';
                    $verifyStatus = "支付成功";
                    if(!$order['trade_no']||$order['status']!=1){
                        $payData = array(
                            'trade_no'=>$trade_no,
                            'success_time'=>curr_time(),
                            'status'=>1
                        );
                        $pay=  D('Pay')->where(array('order_no'=>$order_no))->save($payData);
                        $amount = round($total_fee / ($this->sys_config['SYSTEM_EXRATE'] * 100) ,2);
                        $remark = '充值' . $order_no .',增加现金账户：' . $amount;
                        //记录会员账户变更信息
                        $user = D('User')->where(array('user_no'=>$pay['user_no']))->find();
                        $record = array(
                            'user_no'       => $user['user_no'],
                            'account_type'  => Constants::ACCOUNT_TYPE_CB,
                            'type'          => Constants::ACCOUNT_CHANGE_TYPE_INC,
                            'amount'        => $amount,
                            'balance'       => $user['cb_account'] + $amount,
                            'remark'        => $remark,
                            'add_time'      => curr_time()
                        );
                        M('AccountRecord')->add($record);
                        //变更会员账号信息
                        M('User')->where(array("user_no"=>$pay['user_no']))
                                 ->setInc('cb_account',$amount);
                    }
                }else{
                    if(!$order['trade_no']&&$order['status']!=1){
                        $verifyStatus = "订单支付失败";
                        $payData = array(
                            'trade_no'=>$trade_no,
                            'success_time'=>curr_time(),
                            'status'=>2
                        );
                        D('Pay')->where(array('order_no'=>$order_no))->save($payData);
                    }
                }
            }else{
                $verifyStatus = "订单不存在";
            }
        }else {
            $verifyStatus = "解密失败";
        }
        $this->addLog($verifyStatus);
        return $order_no;
    }
    /**
     * 函数用途描述
     *
     * @param    string  remark  日志备注
     *
     * @since: 2017年1月9日 下午6:02:33
     * @author: lyx
     */
    public function addLog($remark){
        $log = array(
            'role'         => Constants::LOG_ROLE_ADMIN,
            'username'     => 'rongbao',
            'type'         => Constants::LOG_TYPE_OPERATION,
            'remark'       => $remark,
            'operate_time' => curr_time(),
        );
        M('Log')->add($log);
    }

    /**
     * 静态奖金结算
     *
     * @since: 2016年2月23日 下午3:21:44
     * @change xl
     */
    public function staticPrice()
    {
      $userLevel = D('UserLevel')->select();
      $market = D('MarketRecord')->select();
      $flag = false;
       foreach($market as $v)
       {
           foreach($userLevel as $val)
           {
              $rtime = $v['return_time'];
              $ctime =  $val['return_cycle'];
              $amount = ($v['amount']*$val['multiple']/$val['return_number']);
                if($v['user_level_id']==$val['id']&&
                    $amount*$v['return_number']<$val['return_max']&&
                    $v['return_number']<$val['return_number']&&
                    curr_time()<=date('Y-m-d H:i:s',strtotime("{$rtime}+{$ctime} day"))){
                    if(($val['return_max']-$amount*$v['return_number'])<$amount)
                    {
                        $amount = $val['return_max']-$amount*$v['return_number'];
                        $flag = true;
                    }
                    D('ReturnRecord')->data(array('market_record_id'=>$v['id'],
                                                    'user_no'=>$v['user_no'],
                                                     'user_level_id'=>$v['user_level_id'],
                                                      'market_type'=>$v['market_type'],
                                                       'amount'=>$amount,
                                                      'add_time'=>curr_time()
                       ))->add();
                    D('User')->where(array('user_no'=>$v['user_no']))
                             ->setInc('rb_account',$amount);
                    if(($v['return_number']+1)==$val['return_number']||$flag){
                        D('MarketRecord')->where(array('id'=>$v['id']))
                                         ->data(array('return_is_over'=>1,'return_number'=>($v['return_number']+1),'return_time'=>curr_time()))
                                         ->save();
                    }else{
                        D('MarketRecord')->where(array('id'=>$v['id']))
                                         ->data(array('return_number'=>($v['return_number']+1),'return_time'=>curr_time()))
                                         ->save();
                    }
                }
           }
           $flag = false;
       }
    }
    /**
     *查看接收数据
     * @since: 2016年3月11日 下午3:21:44
     * @change xl
     */
    private function writeFile($arr,$attr)
    {
        $myfile = fopen(THINK_PATH.'../Upload/'."testfile.php", "a");
        $txt = curr_time().json_encode($arr).$attr.PHP_EOL;
        fwrite($myfile, $txt);
        fclose($myfile);
    }
}